package com.example.test.handler;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.core.ResolvableType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class JsonListTypeHandler<T extends Object> extends BaseTypeHandler<List<T>> {
    JavaType javaType;

    public JsonListTypeHandler(Class<T> clazz) {
        Assert.notNull(clazz, "JsonTypeHandler class is null");
        ResolvableType resolvableType = ResolvableType.forClass(getClass());
        Type type = resolvableType.as(JsonListTypeHandler.class).getGeneric().getType();
        javaType = getObjectMapper()
                .getTypeFactory()
                .constructParametricType(ArrayList.class, getObjectMapper().constructType(type));
    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    protected String toJson(Object obj) {
        try {
            return getObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return retJson(rs.getString(columnName));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return retJson(rs.getString(columnIndex));
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return retJson(cs.getString(columnIndex));
    }

    public static ObjectMapper getObjectMapper() {
        return JacksonTypeHandler.getObjectMapper();
    }

    protected List<T> retJson(String t) {
        if (StringUtils.isEmpty(t)) return null;
        try {
            return (List<T>) getObjectMapper().readValue(t, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
